package com.ys.erp.stage_marketing_service.utils;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ys.erp.common.enums.RedisKey;
import com.ys.erp.framework.exception.YsException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 微信工具类
 *
 * @author system
 * @date 2025/01/27
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WxUtil {

    @Value("${properties.wx.app-id}")
    private String appId;

    @Value("${properties.wx.app-secret}")
    private String appSecret;
    @Value("${properties.tencent.cos.server}")
    private String server;
    private final RestTemplate restTemplate;

    private final RedisTemplate<String, String> redisTemplate;

    @Value("${properties.wx.qr-code-state}")
    private String qrCodeState;

    private final CosUtil cosUtil;

    /**
     * 获取微信access_token
     *
     * @return access_token
     */
    public String getAccessToken() {
        String redisToken = redisTemplate.opsForValue().get(RedisKey.Enums.WX_ACCESS_TOKEN.getKey());
        if (ObjectUtils.isNotEmpty(redisToken)) {
            return redisToken;
        }

        String url = "https://api.weixin.qq.com/cgi-bin/token?"
                + "grant_type=client_credential"
                + "&appid=" + appId
                + "&secret=" + appSecret;

        String resStr = restTemplate.getForObject(url, String.class);
        JSONObject resJson = JSONObject.parseObject(resStr);

        if (ObjectUtils.isEmpty(resJson)) {
            throw new YsException(-1, "请求微信接口错误");
        }

        if (!resJson.containsKey("access_token") || ObjectUtils.isEmpty(resJson.get("access_token"))) {
            throw new YsException(-1, "获取微信access_token失败：" + resStr);
        }

        String accessToken = resJson.getString("access_token");
        redisTemplate.opsForValue().set(RedisKey.Enums.WX_ACCESS_TOKEN.getKey(), accessToken, 55, TimeUnit.MINUTES);

        log.info("成功获取微信access_token");
        return accessToken;
    }

    public byte[] qrCode(String paramStr, String pagePath) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        JSONObject param = new JSONObject();
        param.put("scene", paramStr);
        param.put("page", pagePath);
        param.put("check_path", false);
        param.put("env_version", qrCodeState);
        param.put("is_hyaline", true);
        HttpEntity<String> entity = new HttpEntity<>(param.toJSONString(), headers);
        ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(url, entity, byte[].class);
        return responseEntity.getBody();
    }

    public String turntableQrCode(String paramStr, String pagePath) {
        ByteArrayInputStream stream = new ByteArrayInputStream(qrCode(paramStr, pagePath));
        String key = null;
        try {
            key = cosUtil.upload(stream, "ignored.png", "lottery");
        } catch (InterruptedException e) {
            log.info("上传二维码失败");
        }
        IoUtil.close(stream);
        return server + "/" + key;
    }
} 